<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item :label="$t('attendance.empName')" prop="empName">
        <el-input
          v-model="queryParams.empName"
          :placeholder="$t('attendance.placeholderEmpName')"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('attendance.deptId')" prop="deptId">
        <treeselect
          v-model="queryParams.deptId"
          :options="enabledDeptOptions"
          :show-count="true"
          :placeholder="$t('attendance.placeholderDeptId')"
          @keyup.enter.native="handleQuery"
          :class="[$ELEMENT.size]"
          :disable-branch-nodes="true"
          :showCount="true"
        />
      </el-form-item>
      <el-form-item
        :label="$t('attendance.attendanceDate')"
        prop="attendanceDate"
      >
        <el-date-picker
          clearable
          v-model="queryParams.attendanceDate"
          type="date"
          value-format="yyyy-MM-dd"
          :placeholder="$t('attendance.placeholderAttendanceDate')"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >{{ $t("common.search") }}</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
          $t("common.reset")
        }}</el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['attendance:attendance:add']"
          >{{ $t("common.add") }}</el-button
        >
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['attendance:attendance:export']"
          >{{ $t("common.export") }}</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="attendanceList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        :label="$t('attendance.empName')"
        align="center"
        prop="empName"
      />
      <el-table-column
        :label="$t('attendance.deptId')"
        align="center"
        prop="deptId"
      >
        <template slot-scope="scope">
          <span>{{
            getDeptName(enabledDeptOptions[0], scope.row.deptId)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('attendance.clockStatus')"
        align="center"
        prop="clockStatus"
      >
        <template slot-scope="scope">
          <el-tag
            :type="['', '', 'warning', 'danger'][scope.row.clockStatus]"
            >{{
              $t("common.attendance_status_" + scope.row.clockStatus)
            }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('attendance.attendanceDate')"
        align="center"
        prop="attendanceDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.attendanceDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('attendance.clockTime')"
        align="center"
        prop="clockTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.clockTime, "{y}-{m}-{d} {h}:{i}")
          }}</span>
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('attendance.workStartTime')"
        align="center"
        prop="workStartTime"
      />
      <el-table-column
        :label="$t('attendance.workEndTime')"
        align="center"
        prop="workEndTime"
      />
      <el-table-column
        :label="$t('common.operate')"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['attendance:attendance:edit']"
            >{{ $t("common.edit") }}</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['attendance:attendance:remove']"
            >{{ $t("common.delete") }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改打卡记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form
        class="g_dialog_form"
        ref="form"
        :model="form"
        :rules="rules"
        label-width="auto"
      >
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item :label="$t('attendance.empName')" prop="empName">
              <el-input
                v-model="form.empName"
                :placeholder="$t('attendance.placeholderEmpName')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('attendance.deptId')" prop="deptId">
              <treeselect
                v-model="form.deptId"
                :options="enabledDeptOptions"
                :show-count="true"
                :placeholder="$t('attendance.placeholderDeptId')"
                :class="[$ELEMENT.size]"
                :disable-branch-nodes="true"
                :showCount="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item
              :label="$t('attendance.attendanceDate')"
              prop="attendanceDate"
            >
              <el-date-picker
                clearable
                v-model="form.attendanceDate"
                type="date"
                value-format="yyyy-MM-dd"
                :placeholder="$t('attendance.placeholderAttendanceDate')"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('attendance.clockTime')" prop="clockTime">
              <el-date-picker
                clearable
                v-model="form.clockTime"
                type="datetime"
                value-format="yyyy-MM-dd hh:mm"
                :placeholder="$t('attendance.placeholderClockTime')"
              >
              </el-date-picker> </el-form-item
          ></el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item
              :label="$t('attendance.workStartTime')"
              prop="workStartTime"
            >
              <el-date-picker
                clearable
                v-model="form.workStartTime"
                type="datetime"
                value-format="yyyy-MM-dd hh:mm"
                :placeholder="$t('attendance.placeholderWorkStartTime')"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('attendance.workEndTime')"
              prop="workEndTime"
            >
              <el-date-picker
                clearable
                v-model="form.workEndTime"
                type="datetime"
                value-format="yyyy-MM-dd hh:mm"
                :placeholder="$t('attendance.placeholderWorkEndTime')"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('attendance.clockStatus')">
              <el-radio-group v-model="form.clockStatus">
                <el-radio
                  v-for="dict in dict.type.sys_attendance_status"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ $t("common.attendance_status_" + dict.value) }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{
          $t("common.confirm")
        }}</el-button>
        <el-button @click="cancel">{{ $t("common.cancel") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { deptTreeSelect } from "@/api/system/user";
import {
  listAttendance,
  getAttendance,
  delAttendance,
  addAttendance,
  updateAttendance,
} from "@/api/attendance/attendance";

export default {
  name: "Attendance",
  dicts: ["sys_attendance_status"],
  components: {
    Treeselect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 打卡记录表格数据
      attendanceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        empName: null,
        deptId: null,
        attendanceDate: null,
        clockStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        empName: [
          {
            required: true,
            message: this.$t("attendance.empNameRequired"),
            trigger: "blur",
          },
        ],
        deptId: [
          {
            required: true,
            message: this.$t("attendance.deptIdRequired"),
            trigger: "blur",
          },
        ],
        attendanceDate: [
          {
            required: true,
            message: this.$t("attendance.attendanceDateRequired"),
            trigger: "blur",
          },
        ],
      },
      enabledDeptOptions: undefined,
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
  },
  methods: {
    /** 查询打卡记录列表 */
    getList() {
      this.loading = true;
      listAttendance(this.queryParams).then((response) => {
        this.attendanceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      const now = new Date();
      let year = now.getFullYear();
      let month = now.getMonth() + 1;
      let day = now.getDate();
      let hour = now.getHours();
      let minute = now.getMinutes();
      this.form = {
        id: null,
        empName: null,
        deptId: null,
        attendanceDate: year + "-" + month + "-" + day,
        attendanceCycle: null,
        workStartTime: year + "-" + month + "-" + day + " 08:00",
        workEndTime: year + "-" + month + "-" + day + " 18:00",
        clockTime: year + "-" + month + "-" + day + " " + hour + ":" + minute,
        location: null,
        clockStatus: "1",
        lateMinutes: null,
        earlyLeaveMinutes: null,
        submitter: null,
        submitTime: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = this.$t("attendance.addTitle");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getAttendance(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = this.$t("attendance.editTitle");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateAttendance(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t("attendance.editSuccess"));
              this.open = false;
              this.getList();
            });
          } else {
            addAttendance(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t("attendance.addSuccess"));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm(this.$t("attendance.deleteConfirm", { ids }))
        .then(function () {
          return delAttendance(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t("attendance.deleteSuccess"));
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "attendance/attendance/export",
        {
          ...this.queryParams,
        },
        `attendance_${new Date().getTime()}.xlsx`
      );
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
        this.enabledDeptOptions = this.filterDisabledDept(
          JSON.parse(JSON.stringify(response.data))
        );
      });
    },
    // 过滤禁用的部门
    filterDisabledDept(deptList) {
      return deptList.filter((dept) => {
        if (dept.disabled) {
          return false;
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children);
        }
        return true;
      });
    },
    //根据部门id获取部门名称
    getDeptName(tree, id) {
      // 根据id查找label的递归方法
      let findLabelById = (tree, id) => {
        if (tree.id == id) {
          return tree.label;
        }
        if (tree.children && tree.children.length) {
          for (let child of tree.children) {
            const result = findLabelById(child, id);
            if (result) return result;
          }
        }
        return null;
      };
      return findLabelById(tree, id);
    },
  },
};
</script>
